/**
 * @author zunqiang.Yi
 * @time 2023-10-21 14:18 PM
 * @description 定义crypto加解密的方法
 * */ 
import { AES,enc } from 'crypto-js'
import { CRYPTO_KEY } from '../config/common.cfg'
/**
 * 加密方法
 * @param msg string 需要加密的字符串
 * @returns string 加密后的字符串
 * */ 
export function enCodeApi(msg:string) :string{
    return AES.encrypt(msg,CRYPTO_KEY).toString()
}

/**
 * 解密密方法
 * @param msg string 需要加密的字符串
 * @returns string 加密后的字符串
 * */ 
export function deCodeApi(msg:string):string{
    return AES.decrypt(msg,CRYPTO_KEY).toString(enc.Utf8)
}

/**
 * 校验是否为手机号
 * @param phone 
 * @returns 
 */
export function validatePhone(phone: number): boolean {
    return /^1[3-9]{1}[0-9]{9}$/.test(phone + '')
}

/**
 * 图片缩放
 * @param {File} _file 需要缩放的file对象
 * @returns Promise<string> 返回的base64字节码
 */
export function scaleImage(_file: File): Promise<string> {
    return new Promise(resolve=>{
        let _fr: FileReader =  new FileReader();
        _fr.onload = function(){
            let _img:HTMLImageElement = new Image()
            _img.onload = function(){
                let _canvas:HTMLCanvasElement = document.createElement('canvas')
                let _ctx:CanvasRenderingContext2D = _canvas.getContext('2d') as CanvasRenderingContext2D;
                let _width:number = 512;
                _canvas.width = _width;
                _canvas.height = _width;
                /** 计算图片缩放比率，得到缩放后的图片高度和宽度 */
                let _destWidth:number;
                let _destHeight:number;
                if(_img.width < _width && _img.height < _width){
                    _destWidth = _img.width;
                    _destHeight = _img.height;
                } else{
                    let _rate = (_img.width > _img.height ? _img.width : _img.height) / _width;
                    _destWidth = _img.width / _rate;
                    _destHeight = _img.height / _rate;
                }
                _ctx.drawImage(_img,0,0,_img.width,_img.height,(_width - _destWidth) / 2,(_width - _destHeight) / 2,_destWidth,_destHeight)
                resolve(_canvas.toDataURL())
            }
            _img.src = _fr.result as string
        }
        _fr.readAsDataURL(_file)
    })
}